#include "TcpClient.hpp"
#include "Sock.hpp"
#include "Protocol.hpp"

#include <iostream>
#include <string>

using namespace protocol_ns;

static void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    std::cout << "Cal client\n";
    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    Sock sock;
    sock.Socket();
    int n = sock.Connect(serverip, serverport);
    if (n != 0)
        return 1;

    logMessage(DEBUG, "Connect 成功！");

    std::string buffer;
    while (true)
    {
        Request req;
        std::cout << "Data1>>";
        std::cin >> req._x;
        std::cout << "Data2>>";
        std::cin >> req._y;
        std::cout << "op>>";
        std::cin >> req._op;
        std::cout << "test: " << req._x << req._op << req._y << std::endl;

        // 序列化
        std::string sendString;
        req.Serialize(&sendString);
        // 添加报头
        sendString = AddHeader(sendString);
        // 发送
        send(sock.Fd(), sendString.c_str(), sendString.size(), 0);

        // 获取服务器响应
        std::string package;
        int n = 0;
    START:
        n = ReadPackage(sock.Fd(), buffer, &package);
        if (n == 0)
            goto START;
        else if(n < 0)
            break;
        // 去掉响应的报头
        package = RemoveHeader(package, n);
        // 反序列化
        Response resp;
        resp.Deserialize(package);

        std::cout << "Result: " << resp._result << "[code: " << resp._code << "]\n";
    }

    sock.Close();
    return 0;
}